import axios from 'axios';
import router from '../router/index';
import store from '@/store/store';
import { Message } from 'element-ui';
import { Loading } from 'element-ui';
let loadingCount = 0;
let loadingInstance;
export const baseURL = '/orderPlusApi';
axios.defaults.timeout = 36000000;
axios.defaults.baseURL = baseURL; //这是调用数据接口
axios.defaults.withcRDentials = true; //让ajax携带cookie
axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8;';
function handleLoadingClose() {
  loadingCount--;
  if (loadingCount === 0) {
    loadingInstance.close();
  }
}
// 请求拦截器
axios.interceptors.request.use(
  config => {
    const token = store.state.token;
    config.headers.Authorization = token;
    if (config.url !== 'business/payOrder/queryPayOrder') {
      if (loadingCount === 0) {
        loadingInstance = Loading.service({ fullscreen: true, text: '加载中...' });
      }
      loadingCount++;
    }
    return config;
  },
  error => {
    return Promise.error(error);
  }
);
// 响应拦截器
axios.interceptors.response.use(
  response => {
    handleLoadingClose();
    const urlArr = ['business/productBrandArticleNo/add', 'business/productBrand/add', 'business/mail/send', 'business/productSpecification/add', 'business/unit/add'];
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据 否则的话抛出错误
    if ((response.status === 200 && response.data.code === 200) || urlArr.includes(response.config.url)) {
      return Promise.resolve(response);
    } else if (response.status === 200 && response.data.code === 401) {
      router.push({ path: '/login' });
    } else {
      Message.error(response.data.msg);
      return Promise.reject(response);
    }
  },
  // 服务器状态码不是200
  error => {
    handleLoadingClose();
    if (error.response.status) {
      return Promise.reject(error.response);
    }
  }
);
export function get(urls, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(urls, { params })
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}
export function post(urls, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(urls, params)
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}
export function postFile(urls, params) {
  return new Promise((resolve, reject) => {
    let config = { headers: { 'Content-Type': 'multipart/form-data' } };
    axios
      .post(urls, params, config)
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}
export function getFile(urls, params) {
  return new Promise((resolve, reject) => {
    let config = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } };
    axios
      .post(urls, params, config)
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}
